var plog = require("./plog");
var plib = require("./plib");

module.exports.Msgs = function(_app, _channelname , _rlist, _msgname, _msg)
{
	var _channelServer = _app.get('channelService');
  var channel = _app.get('channelService').getChannel(_channelname, false);
  var mlist = new Array();
    for(var i = 0; i < _rlist.length; i ++) //k in _rlist)
	{
		var m = channel.getMember(_rlist[i]);
		if(typeof m != 'undefined')
		{
			mlist.push({
				uid:_rlist[i], 
				sid:m['sid']				});
		} else {
			plog.out("Warn: " + _rlist[i] + " already offline(channelname:" + _channelname + "msg:" + _msgname);
		}
	}	
	
	_channelServer.pushMessageByUids(_msgname, _msg, mlist);

}
// select an item from list based on key
module.exports.pushMessage = function(_channelServer, _channelname, _rlist, _msgname, _msg) {
	var channel = _channelServer.getChannel(_channelname, false);
	var mlist = new Array();
	plog.out(_rlist);
	for(var i = 0; i < _rlist.length; i ++) //k in _rlist)
	{
		mlist.push({
			uid:_rlist[i], 
			sid:channel.getMember(_rlist[i])['sid']				});
	}	
	plog.out("=====================================");
	plog.out(mlist);
	_channelServer.pushMessageByUids(_msgname, _msg, mlist);
};

module.exports.Msg = function(_app, _channelname, _rid, _msgname, _msg) {
	var _channelServer = _app.get('channelService');
	var channel = _app.get('channelService').getChannel(_channelname, false);
	var mlist = new Array();
	//plog.out(plib.objdump(channel.getMember(_rid)));
	var mm = channel.getMember(_rid);
	if(mm !=  null){
	mlist.push({
		uid:_rid, 
		sid:mm['sid']});
	_channelServer.pushMessageByUids(_msgname, _msg, mlist);
	}

}
module.exports.pushOneMessage = function(_channelServer, _channelname, _rid, _msgname, _msg) {
	var channel = _channelServer.getChannel(_channelname, false);
	if(channel == null)
	{ plog.out("error, can not find the channel");
	}
	var mlist = new Array();
	//plog.out(plib.objdump(channel.getMember(_rid)));
	var mm = channel.getMember(_rid);
	if(mm !=  null){
	mlist.push({
		uid:_rid, 
		sid:mm['sid']});
	_channelServer.pushMessageByUids(_msgname, _msg, mlist);
	}
};


/*
module.exports.SessionSet = function(_app, _rid, _field, _val)
{
	var sessionService = _app.get('sessionService');
	var rss = sessionService.getByUid(_rid)
	if(!! rss) {
		plog.out("can not get session of rid");
		return 1;
	}
	
	rss.set(_field, _val);
	rss.push(_field, function(err) {
		if(err){
			plog.out("err set " + _field + " as " + val);		
		}
	});
}
module.exports.SessionGet = function(_app, _rid, _field) 
{
	var sessionService = _app.get('sessionService');
	var rss = sessionService.getByUid(_rid)
	if(!! rss) {
		plog.out("can not get session of rid");
		return null;
	}
	return rss.get(_field);
}


module.exports.GetBESession = function(_app, _rid)
{
	var bss = _app.get('backendSessionService');
	var s =  bss.getByUid(_rid);
	if(s == null)
		plog.out("s is empty");
	else 
		plog.out("we find the s");
	return s;
}

*/
